import PropTypes from 'prop-types';
import { useState } from 'react';
import './Cart.css';
import ItemType from '../types/item';
import CartRow from './CartRow';

function Cart({ cart, items, dispatch }) {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [zipCode, setZipCode] = useState('');
  const subtotal = cart.reduce((acc, it) => {
    const item = items.find((i) => i.itemId === it.itemId);
    const price = item.salePrice ?? item.price;
    return acc + price * it.quantity;
  }, 0);
  const submitOrder = (event) => {
    event.preventDefault();
    console.log(`name:${name}`);
    console.log(`phone:${phone}`);
    console.log(`zipcode:${zipCode}`);
  };

  const taxPercentage = parseInt(zipCode.substring(0, 1) || '0', 10) + 1;
  const taxRate = taxPercentage / 100;
  const tax = subtotal * taxRate;
  const total = subtotal + tax;

  const setFormattedPhone = (newNumber) => {
    const digits = newNumber.replace(/\D/g, '');
    let formatted = digits.substring(0, 3);
    if (digits.length === 3 && newNumber[3] === '-') {
      formatted = `${formatted}-`;
    } else if (digits.length > 3) {
      formatted = `${formatted}-${digits.substring(3, 6)}`;
    }
    if (digits.length === 6 && newNumber[6] === '-') {
      formatted = `${formatted}-`;
    } else if (digits.length > 6) {
      formatted = `${formatted}-${digits.substring(6, 10)}`;
    }
    setPhone(formatted);
  };

  const isFormValid = zipCode.length === 5 && name.trim();

  return (
    <div className="cart-component">
      <h2>Your Cart</h2>
      {cart.length === 0
        ? (<div> Your cart is empty</div>)
        : (
          <>
            <table>
              <thead>
                <tr>
                  <th>Quantity</th>
                  <th>Item</th>
                  <th>Subtotal</th>
                </tr>
              </thead>
              <tbody>
                {cart.map((item) => (
                  <CartRow
                    key={item.itemId}
                    cartItem={item}
                    items={items}
                    dispatch={dispatch}
                  />
                ))}
              </tbody>
            </table>
            <div>
              Subtotal: $
              {subtotal.toFixed(2)}
            </div>
            {zipCode.length === 5
              ? (
                <>
                  <div>
                    Tax: $
                    {tax.toFixed(2)}
                  </div>
                  <div>
                    Total: $
                    {total.toFixed(2)}
                  </div>
                </>
              ) : (<div className="warning">Enter zipCode to get total.</div>)}
            <h2>Checkout</h2>
            <form onSubmit={submitOrder}>
              <label htmlFor="name">
                Name
                <input
                  id="name"
                  type="text"
                  value={name}
                  onChange={(event) => setName(event.target.value)}
                  required
                />
              </label>
              <label htmlFor="phone">
                Phone number
                <input
                  id="phone"
                  type="tel"
                  value={phone}
                  onChange={(event) => setFormattedPhone(event.target.value)}
                />
              </label>
              <label htmlFor="zipcode">
                Zip code
                <input
                  id="zipcode"
                  type="text"
                  maxLength="5"
                  inputMode="numeric"
                  value={zipCode}
                  onChange={(event) => setZipCode(event.target.value)}
                  required
                />
              </label>
              <button type="submit" disabled={!isFormValid}>Order Now</button>
            </form>
          </>
        )}
    </div>
  );
}

Cart.propTypes = {
  cart: PropTypes.arrayOf(
    PropTypes.shape({
      quantity: PropTypes.number.isRequired,
      itemId: PropTypes.string.isRequired,
    }),
  ).isRequired,
  items: PropTypes.arrayOf(ItemType).isRequired,
  dispatch: PropTypes.func.isRequired,
};

export default Cart;
